<?php
/**
 * User: @lose
 * Date: 2019-10-23
 * Time: 16:59
 */

namespace Frieza\Modules\Photo\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\Album\AlbumListModel;
use Doraemon\amqp\CommunityQueue;
use Doraemon\cache\FeaturePool as cFeaturePool;
use Doraemon\cache\MachineQuality as cMachineQuality;
use Doraemon\cache\Photos as cPhotos;
use Doraemon\cache\Queue;
use Doraemon\model\AdminAccount\AdminAccountOperate;
use Doraemon\model\AdmNoteFeature;
use Doraemon\model\AdmNoteOutlineLog;
use Doraemon\model\Content\ContentCategoryLabel as mContentCategoryLabel;
use Doraemon\model\Content\ContentRelatedCategory as mContentRelatedCategory;
use Doraemon\model\ContentSignExtend as PhotosExtend;
use Doraemon\model\Es\UserPortrait;
use Doraemon\model\Member;
use Doraemon\model\Photos as dbPhoto;
use Doraemon\model\Photos as DbPhotos;
use Doraemon\model\Photos as mPhotos;
use Doraemon\model\RecheckQualityDetail;
use Doraemon\model\RecheckQualityTask;
use Doraemon\model\Task;
use Doraemon\model\Task\TaskBase;
use Doraemon\model\Task\UserTaskInfo as mUserTaskInfo;
use Doraemon\model\Topic\TopicActivity;
use Doraemon\service\AdminTag\Schedule;
use Doraemon\service\AdmNote;
use Doraemon\service\Circle\PhotosCircle;
use Doraemon\service\Content\ContentRelatedCategory as sContentRelatedCategory;
use Doraemon\service\ContentCategory;
use Doraemon\service\DecorationTask\Read;
use Doraemon\service\Note\NoteHandle;
use Doraemon\service\Photo\RecheckQuality;
use Doraemon\service\Photo\RecheckQualityDetail as sRecheckQualityDetail;
use Doraemon\service\Photos;
use Doraemon\service\PhotoScreen;
use Doraemon\service\Task\Task as sTask;
use Doraemon\service\UserGrowth\AutoAction;
use Doraemon\service\Videos\Videos as sVideos;
use Doraemon\tools\Creator\GrowthConfig as tGrowthConfig;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\PointConfig;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Form;
use Frieza\Modules\Photo\Extensions\Filter as SearchFilter;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\InfoBox;


class PhotoReCheckQualityController extends Controller
{
    public const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /**
     * 复审&质检列表页
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content)
    {
        $admin_name = Admin::user()->username;
        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $search = $request->all();

        $list = RecheckQuality::getList($page, $pageSize, $search);
        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel,$admin_name) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                if (!in_array($admin_name, ['zhouchao'])){
                    $grid->disableCreateButton();
                }

                $grid->filter(function ($filter) {
                    $filter->disableIdFilter();
                    $filter->column(1/2, function ($filter){
                        $filter->equal('id', '任务ID')->placeholder("请输入任务ID");
                        $filter->equal('task_status', '状态')->select(RecheckQualityTask::TASK_STATUS);
                    });
                });

                $grid->column('id','任务ID')->sortable();
                $grid->column('task_name','任务名称');
                $grid->column('task_num','任务内容量');
                $grid->column('branch', '执行周期')->display(function () {
                    return  '<div class="span-label" style="margin-bottom: 5px"><span class="label label-success">'. $this->plant_execution_start_time.'</span></div>
                             <div class="span-label" style="margin-bottom: 5px"><span class="label label-success">'. $this->plant_execution_end_time.'</span></div>';
                });
                $grid->column('remark','备注');
                $grid->column('task_status','任务状态')->using(RecheckQualityTask::TASK_STATUS)->label([
                    1 => 'danger',
                    2 => 'info',
                    3 => 'default',
                ]);

                $grid->actions(function ($actions) use ($admin_name){
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();

                    //权限

                    if (in_array($admin_name, ['zhouchao'])){
//                        //管理员
                       if($actions->row->task_status == 1){
                           $actions->prepend('<a class="fa reload-data delete_task" data-id="'.$actions->row->id.'" data-opt = "删除任务" href="javascript:;" >删除任务</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                          if($actions->row->check_start_time == '0000-00-00 00:00:00'){
                              $actions->prepend('<a  href="/admin/photo/photorecheckquality/index/edit/'.$actions->row->id.'" >修改任务</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                          }
                        }
                       else{
                           if( $actions->row->task_status == 2){
                               $actions->prepend('<a class="fa reload-data all_finish" data-id="'.$actions->row->id.'" data-opt = "质检完成" >质检完成</a>');
                           }

                           $actions->prepend('<a href="/admin/photo/photorecheckquality/checktaskindex?task_id='.$actions->row->id.'" >查询结果及质检</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');

                       }
                    }else{

                        //员工操作
                        if($actions->row->task_status == 1){
                            $actions->prepend('<a class="fa reload-data execute_task" data-id="'.$actions->row->id.'" data-opt = "提交完成">提交完成</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                            $actions->prepend('<a  href="/admin/photo/photorecheckquality/checkindex?task_id='.$actions->row->id.'" >执行任务</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                        }

                    }

                });
            });

        Admin::script(
            <<<EOT
            //删除任务
            $('.delete_task').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认要删除吗，此操作不可逆!!!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/admin/photo/photorecheckquality/deletetask/' + id,
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });
        //提交完成任务
         $('.execute_task').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认提交完成任务？操作不可逆!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/admin/photo/photorecheckquality/executetask/' + id,
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });
        
        //提交质检完成
         $('.all_finish').unbind('click').click(function() {
            var id = $(this).data('id');
            swal({
                title: "确认质检完成？操作不可逆!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/admin/photo/photorecheckquality/allfinish/' + id,
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });
            
       
EOT);

        return $content
            ->header('复审&质检')
            ->description(' ')
            ->breadcrumb(['text' => '复审&质检','url'=>'/photo/photorecheckquality/index'],
                ['text' => '详情'])
            ->row($gridList);

    }

    public function add(Request $request, Content $content)
    {
        $request = $request->all();
        return $content
            ->header('创建任务')
            ->breadcrumb(['text' => '复审&质检','url'=>'/photo/photorecheckquality/index'],
                ['text' => '创建任务']
            )
            ->body($this->editAction($request, $id = 0));
    }

    public function edit(Request $request, Content $content, $id)
    {

        $request = $request->all();
        return $content
            ->header('修改任务')
            ->breadcrumb(['text' => '复审&质检','url'=>'/photo/photorecheckquality/index'],
                ['text' => '修改任务']
            )
            ->body($this->editAction($request, $id));


    }

    /**
     * 创建/修改任务任务页面
     */
    public  function editAction($request, $id = 0)
    {
        if($id != 0) {
            //修改
            $data = RecheckQualityTask::getById($id);
            if($data['select_user_type']){
                $data['select_user_type'] = json_decode($data['select_user_type'], true, 512, JSON_THROW_ON_ERROR);
            }

            if($data['select_score']){
                $data['select_score'] = json_decode($data['select_score'], true, 512, JSON_THROW_ON_ERROR);
            }
           $aCheckedUserType =  $data['select_user_type'];
            unset($data['select_user_type']);
            $form = new Form($data);
            $form->hidden('id');
            $categoryFirstId =  $data['category_first_id'];
        } else {
            //添加
            $form = new Form(new RecheckQuality);
            $categoryFirstId = request('category_first_id', null);
        }
        $categoryLabelSecond = [];
        if ($categoryFirstId) {
            $categoryLabelSecond = mContentCategoryLabel::getListFormatKey($categoryFirstId, 2);
        }
        $categoryLabelFirst = mContentCategoryLabel::getListFormatKey(0, 1);
        $categoryLabelFirst[0] = '未打标签';
        ksort($categoryLabelFirst);

        $form->text('task_name', '任务名称')->required();;
        $form->datetime('plant_execution_start_time','质检开始时间')->format('YYYY-MM-DD HH:mm:ss')->default('')->required();
        $form->datetime('plant_execution_end_time','质检结束时间')->format('YYYY-MM-DD HH:mm:ss')->default('')->required();
        $form->text('remark', '备注');
        $form->datetime('select_start_time','发图开始时间')->format('YYYY-MM-DD HH:mm:ss')->default('')->required();
        $form->datetime('select_end_time','发图结束时间')->format('YYYY-MM-DD HH:mm:ss')->default('')->required();
        if($id != 0) {
            $form->checkbox('select_user_type', '用户身份')->options(Member::$typeDesc)->checked($aCheckedUserType);
        }else{
            $form->checkbox('select_user_type', '用户身份')->options(Member::$typeDesc);
        }
        $form->checkbox('select_score', '分数')->options(Schedule::SCORE_DESC);
        $form->select('category_first_id', '一级品类')->options($categoryLabelFirst)->load('category_second_id', route('getCategoryLabel'));
        $form->select('category_second_id', '二级品类')->options($categoryLabelSecond);
        $form->text('select_check_ratio', '比例')->pattern('\b([1-9]|[1-9][0-9]|100)\b')->help('填写 1-100 单位为%')->default(100);
        $url = 'admin/photo/photorecheckquality/index/editsubmit?id=' . $id;
        $form->html('<div style="text-align:center;padding-top: 30px" >
                <input class="btn btn-sm btn-success grid-row-refuse " value="任务包内实时内容量查询" style="margin-right: 100px;width: 160px;height: 35px">
                </div>');
        Admin::script(
           <<<EOT

        $('.grid-row-refuse').unbind('click').click(function() {
            var select_start_time = $('input[name="select_start_time"]').val();
            var select_end_time = $('input[name="select_end_time"]').val();

            let arr = [];
            $('input[class="select_user_type"]:checked').each(function(index, element) {
                arr.push($(this).val())
            });
//            let select_user_type = arr.join(',');
            let select_user_type = arr;
            let arry = [];
            $('input[class="select_score"]:checked').each(function(index, element) {
                arry.push($(this).val())
            });
//            let select_score = arry.join(',');
            let select_score = arry;
            
            let category_first_id = $('select[name="category_first_id"]').val();
            if(category_first_id == 0){
                category_first_id = ''
            }

            if(select_start_time == null || select_start_time == undefined || select_start_time == "" || select_end_time == null || select_end_time == undefined || select_end_time == ""){
                alert('请选择发图开始/结束时间')
                return false
            }
            
            let category_second_id =$('select[name="category_second_id"]').val();
            
            let select_check_ratio = $('input[name="select_check_ratio"]').val();

            layer.open({
                type: 2,
                title: '任务包内实时内容量查询',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['400px', '150px'],
                content: '/admin/photo/photorecheckquality/index/getNum?select_start_time='+select_start_time +'&select_end_time=' +select_end_time + 
                '&select_user_type='+select_user_type+'&select_score='+select_score+'&category_first_id='+category_first_id+'&category_second_id=' +category_second_id +'&select_check_ratio='+select_check_ratio,
            });
        });
EOT);

        $form->action(url('admin/photo/photorecheckquality/index/editsubmit'));



        return $form->render();

    }

    /**
     * 提交创建任务数据
     */
    public function editSubmit(Request $request)
    {
        $data = $request->all();
//        var_dump($data);die;


        unset($data['_token']);

        if($data['select_user_type']){

            foreach ($data['select_user_type'] as $key =>$val){
                if($val == ''){
                    unset($data['select_user_type'][$key]);
                }
            }

            $data['select_user_type'] = json_encode($data['select_user_type'], JSON_THROW_ON_ERROR);
        }
        if($data['select_score']) {
            foreach ($data['select_score'] as $key =>$val){
                if($val == ''){
                    unset($data['select_score'][$key]);
                }
            }
            $data['select_score'] = json_encode($data['select_score'], JSON_THROW_ON_ERROR);
        }
        $data['status'] = RecheckQualityTask::STATUS_NORMAL;
        //没有数据提示
        $data['task_num'] = $this->getTaskNum($request);
        if( $data['task_num'] < 1 ){
            $error = new MessageBag(['title' => '该任务没有获取到数据']);
            return back()->with(compact('error'));
        }

        if(isset($request['id']) && $request['id']) {
            //修改
            $iTaskId = $request['id'];
            $data['edittime'] = date('Y-m-d H:i:s');
            RecheckQualityTask::updateById($request['id'], $data);
            //删除老数据
            RecheckQualityDetail::deleteByTaskid($request['id']);
        } else {
            //添加
            $data['addtime'] = date('Y-m-d H:i:s');
            $iTaskId = RecheckQualityTask::add($data);
            if($iTaskId === false){
                $error = new MessageBag(['title' => '添加任务失败']);
                return back()->with(compact('error'));
            }
        }
        //将获取的数据写入详情表
        $rs =  self::setNotesToDetail($request,$iTaskId, $data['task_num']);
        if($rs) {
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return redirect('/admin/photo/photorecheckquality/index')->with(compact('success'));
        }

        $error = new MessageBag([
            'title' => '提交失败'
        ]);
        return redirect('/admin/photo/photorecheckquality/index')->with(compact('error'));
    }

    /**
     * 管理员删除任务
     * @param Request $request
     * @return array
     */
    public function deleteTask(Request $request): array
    {
        $iId = $request['id'];

        $aData = [
            'status' => RecheckQualityTask::STATUS_DELETE
        ];
        $result = RecheckQualityTask::updateById($iId,$aData);

        if($result){
            //删除老数据
            RecheckQualityDetail::deleteByTaskid($iId);

            return [
                'code' => 1,
                'msg' => "删除成功"
            ];
        }
        return [
            'code' => 0,
            'msg' => "删除失败"
        ];
    }

    /**
     * 员工提交完成任务
     */
    public function finishTask(Request $request): array
    {
        $iId = $request['id'];
        $aData = [
            'check_end_time'=> date('Y-m-d H:i:s'),
            'task_status' => RecheckQualityTask::STATUS_UNINSPECTION
        ];
        $result = RecheckQualityTask::updateById($iId,$aData);
        if($result){
            return [
                'code' => 1,
                'msg' => "提交成功"
            ];
        }

        return [
            'code' => 0,
            'msg' => "提交失败"
        ];
    }

    /**
     * 提交质检完成任务
     */
    public function allFinish(Request $request): array
    {
        $iId = $request['id'];
        $aData = [
            'task_status' => RecheckQualityTask::STATUS_INSPECTION
        ];
        $result = RecheckQualityTask::updateById($iId,$aData);
        if($result){
            return [
                'code' => 1,
                'msg' => "提交成功"
            ];
        }

        return [
            'code' => 0,
            'msg' => "提交失败"
        ];
    }


    /**
     * 查看任务包内实时内容量查询
     * @param Request $request
     * @return void
     */
    public function getNum(Request $request)
    {

        $sUserType = $request->input('select_user_type');
        if (isset($sUserType) && $sUserType != '' && is_string($sUserType)) {
            if(false === strpos($sUserType, ',')){
                $request->merge([
                    'user_type' => [$sUserType]
                ]);
            }else{
                $request->merge([
                    'user_type' => explode(',',$sUserType)
                ]);
            }
        }

        $sSelectScore = $request->input('select_score');
        if (isset($sSelectScore) && is_string($sSelectScore)) {
            if(false === strpos($sSelectScore, ',')){
                $request->merge([
                    'score' => [$sSelectScore]
                ]);
            }else{
                $request->merge([
                    'score' => explode(',',$sSelectScore)
                ]);
            }
        }

        if ($request->input('select_start_time') &&  $request->input('select_end_time')) {
            $request->merge([
                'release_time' => ['start'=>$request->input('select_start_time'),'end'=>$request->input('select_end_time')]
            ]);
        }
        //默认获取全部类型
        $request->merge([
            'search_photo_type' =>Schedule::SEARCH_PHOTO_TYPE_ALL,
            'main'=>Schedule::SEARCH_MAIN_DESC
        ]);

        $iReturnNum =  self::getSearchNum($request);

        return '圈选条件下任务量为:'.$iReturnNum;
    }

    /**
     * 查看任务包内实时内容量查询
     * @param Request $request
     * @return void
     */
    public function getTaskNum(Request $request)
    {
        if($request->input('category_first_id') == 0){
            $request->merge([
                'category_first_id' => ''
            ]);
        }
        $sUserType = $request->input('select_user_type');
        if (isset($sUserType) && $sUserType[0] !='' ) {
            $request->merge([
                'user_type' => $request->input('select_user_type')
            ]);
        }

        $sSelectScore = $request->input('select_score');
        if (isset($sSelectScore) ) {
            $request->merge([
                'score' => $request->input('select_score')
            ]);
        }

        if ($request->input('select_start_time') &&  $request->input('select_end_time')) {
            $request->merge([
                'release_time' => ['start'=>$request->input('select_start_time'),'end'=>$request->input('select_end_time')]
            ]);
        }
        //默认获取全部类型
        $request->merge([
            'search_photo_type' =>Schedule::SEARCH_PHOTO_TYPE_ALL,
            'main'=>Schedule::SEARCH_MAIN_DESC
        ]);
        return self::getSearchNum($request);
    }

    public static function getSearchNum($request){
        $searchResult = self::getSearchResult($request);
        if(!empty($request->input('select_check_ratio'))){
            $ratio = $request->input('select_check_ratio') /100;
            $iReturnNum = (int)floor($searchResult['total'] * $ratio);
        }else{
            $iReturnNum = $searchResult['total'];
        }
        return $iReturnNum;
    }

    /**
     * 任务复审列表
     */
    public function checkIndex(Request $request, Content $content)
    {
        $params = $request->all();
        $iTaskId = $params['task_id'];

        $aTaskInfo = RecheckQualityTask::getById($iTaskId);
        $aTaskInfo['check_num'] = self::getIscheckNum($iTaskId);
        //执行任务修改开始时间
        if($aTaskInfo['check_start_time'] === '0000-00-00 00:00:00'){
            RecheckQualityTask::updateById($iTaskId,['check_start_time'=>date('Y-m-d H:i:s')]);
        }
        $aWhere = ['task_id' =>$iTaskId];
        $aWhere['ORDER'] = ['is_check' => 'ASC'];

        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $aTaskDetailList = sRecheckQualityDetail::getList($page, $pageSize, $aWhere);

        $total = $aTaskDetailList['total'];

        $ids = array_column($aTaskDetailList['list'],'obj_id');

        $aDetailList = array_column($aTaskDetailList['list'],null,'obj_id');

        $photos = Photos::getPhotos($ids); // 通过id获取图片信息
        // 获取装修日记
        $diaryList = $diaryIds = $circleList = $circleIds = [];
        foreach ($photos as $photo) {
            if ($photo['type'] == dbPhoto::TYPE_DIARY) {
                $diaryIds[] = $photo['id'];
            }
            if ($photo['type'] == dbPhoto::TYPE_CIRCLE) {
                $circleIds[] = $photo['id'];
            }
        }

        if ($diaryIds) {
            $diaryList = Read::getDiaryByDiaryIds($diaryIds);
        }
        if ($circleIds) {
            $circleList = PhotosCircle::selectPhotoCircle($circleIds);
        }

        //用户信息
        $uids = empty($photos) ? [] : array_column($photos, 'uid');
        $user_infos = Member::getUserInfoByIds($uids);
        $user_infos_regular = [];
        if ($user_infos && is_array($user_infos)) {
            foreach ($user_infos as $user_info) {
                $user_infos_regular[$user_info['uid']] = $user_info;
            }
        }

        //用户等级信息
        $user_levels = UserPortrait::getUserLevelByUIds(array_values(array_unique($uids)));
        //特征信息
        $features = AdmNoteFeature::getFeatureByIds($ids);
        $features_arr = [];
        if ($features && is_array($features)) {
            foreach ($features as $features_info) {
                $features_arr[$features_info['note_id']][] = $features_info['feature'];
            }
        }
        $features_regular = [];
        if ($features_arr && is_array($features_arr)) {
            foreach ($features_arr as $note_id => $feature) {
                $features_regular[$note_id] = implode(',', $feature);
                $features_regular[$note_id] = array_unique(explode(',', $features_regular[$note_id]));
                $features_regular[$note_id] = implode(',', $features_regular[$note_id]);
            }
        }

        $admin_likes = [];
        $likes = AdminAccountOperate::getByObjIds($ids, AdminAccountOperate::ACCOUNT_TYPE_LIKE);
        if ($likes && is_array($likes)) {
            foreach ($likes as $like) {
                $admin_likes[$like['obj_id']] = (string)Admin::user()->find($like['admin_id'])->name;
            }
        }

        //获取社区特征分类
        $categoryList = sContentRelatedCategory::getTypesByObjIds($ids);
        $categoryLabelAll = mContentCategoryLabel::getListFormatKey(0, 0, 0);
        // 获取note关联的wiki
        $wiki_map = Photos::getWikiListMapByIds($ids);
        //获取扩展信息
        $extend_map = [];
        $extend_info = PhotosExtend::getExtendInfoByNoteIds($ids);
        if ($extend_info && is_array($extend_info)) {
            foreach ($extend_info as $value) {
                $extend_map[$value['obj_id']] = $value;
            }
        }
        if ($ids) {
            $machineQuality = cMachineQuality::getItems($ids); // 获取机器打分信息
        }

        $i = 1;
        foreach ($photos as &$info) {
            $info['photo_id'] = $info['id'];
            $categoryFirstId = 0;
            $categorySecondId = 0;
            $categorySource = 2;
            if($aDetailList[$info['photo_id']]['score_check'] == RecheckQualityDetail::UNCHECK){
                $info['admin_score']  = 0;
            }
            if ($aDetailList[$info['photo_id']]['category_check'] == RecheckQualityDetail::CHECKED && isset($categoryList[$info['photo_id']])) {
                $cateInfo = $categoryList[$info['photo_id']];
                $categoryFirstField = 'category_first_id';
                $categorySecondField = 'category_second_id';
                if ($cateInfo['source'] == 1) {//机器
                    $categoryFirstField = 'machine_category_first_id';
                    $categorySecondField = 'machine_category_second_id';
                    $categorySource = 1;
                }
                $categoryFirstId = $categoryList[$info['photo_id']][$categoryFirstField];
                $categorySecondId = $categoryList[$info['photo_id']][$categorySecondField];
            }

            $info['id'] = $i;

            $info['detail_id'] = $aDetailList[$info['photo_id']]['id'];

            $info['user_info'] = $user_infos_regular[$info['uid']];
            $info['admin_like'] = (string)$admin_likes[$info['photo_id']];
            $info['remark'] =  $this->highLight($info['remark']);
            $info['features'] = $features_regular[$info['photo_id']];
            $info['user_levels'] = $user_levels[$info['uid']];
            $info['category_first'] = $categoryFirstId;
            $info['category_second'] = $categorySecondId;
            $info['category_source'] = $categorySource;
            if ($info['show_type'] == DbPhotos::SHOW_TYPE_VIDEO) {
                $videoInfo = sVideos::getVideoCoverInfoById($info['video_id']);
                $info['expand'] = $this->_getVideoExpand($videoInfo, $wiki_map[$info['photo_id']]['list']);
            } else {
                $picInfos = json_decode($info['pic_list'], true) ?: [];
                $info['expand'] = $this->_getPicExpand($picInfos, $wiki_map[$info['photo_id']]['list']);
            }
            $info['expand'] .= $this->_getDivLine();
            if ($info['type'] == dbPhoto::TYPE_DIARY) {
                $info['title'] = !empty($info['title']) ? $info['title'] . "---". $diaryList[$info['photo_id']]['title'] : $diaryList[$info['photo_id']]['title'];
                $info['task_id'] = $diaryList[$info['photo_id']]['task_id'];
            }
            if ($info['type'] == dbPhoto::TYPE_CIRCLE) {
                $info['name'] = $circleList[$info['photo_id']]['circle_name'];
                $info['task_id'] = $circleList[$info['photo_id']]['circle_id'];
            }
            $info['is_business'] = $extend_map[$info['photo_id']]['is_business'] ?: 0;
            $info['display_business'] = $extend_map[$info['photo_id']]['is_display_business'] ?: 0;
            $info['machine_recognition'] = $machineQuality[$info['photo_id']]??0;
            $i++;
        }

        $options = [
            'perPage' => $request->input('per_page') ?: 20
        ];
        $gridModel = new pGridDataModel($photos, $total, $options);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($categoryLabelAll,$aTaskInfo) {

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();
            $grid->disableFilter();


            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

//            $grid->tools(function ($tools)use($aTaskInfo) {
//                $tools->append("<html><span>任务内容量：".$aTaskInfo['task_num']."</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
//<span>已经复审内容量：".$aTaskInfo['check_num'] ."</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>截止时间：".$aTaskInfo['plant_execution_end_time']."</span></html> ");
//            });
//            $grid->filter(function (Grid\Filter $filter) {
//                $filter->disableIdFilter();
//            });



            $grid->column('photo_id', 'NOTE_ID')->expand(function () {
                return $this->expand;
            }, true)->width(90);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('admin_like', '额外信息')->display(function () {
                $userInfo = $this->user_info;
                if ($userInfo['type'] != Member::AUTH_USER_DESIGNER && $userInfo['type'] != Member::AUTH_USER_UNAUTH_DESIGNER) {
                    if (empty($this->admin_like)) {
                        $like_btn = "<a href='javascript:;' class='btn btn-default addLike'  data-note-id='$this->photo_id' id='like$this->photo_id'>点赞</a>";
                    } else {
                        $like_btn = "<a href='javascript:;' class='btn btn-success'  data-note-id='$this->photo_id' id='like$this->photo_id'>$this->admin_like 已赞</a>";
                    }
                }
                $detail = "<a href='http://manage.haohaozhu.me/Admin/Photos/detail/photo_id/$this->photo_id' target='_blank' >图片详情</a><br>";
                $log = "<a href='/admin/photo/photoAuditLog?&id=$this->photo_id' target='_blank' >审核日志</a><br>";
                $copy_btn = "<a href='javascript:;' class='btn btn-default copyH5'  data-id='$this->photo_id' >复制链接</a>";
                // 一部分员工，是兼职，但又得有正式员工的权限
                if (Admin::user()->isRole('partime.user') && !Admin::user()->can('part_time.business')) {
                    if ($like_btn) {
                        return $detail . $log . $like_btn . "<br><br>" . $copy_btn;
                    }
                    return $detail . $log . "<br><br>" . $copy_btn;
                }
                if ($this->is_business) {
                    $businessBtn = "<a href='javascript:;' class='btn btn-success addBusiness'  data-note-id='$this->photo_id' id='business$this->photo_id'>软广</a>";
                } else {
                    $businessBtn = "<a href='javascript:;' class='btn btn-default addBusiness'  data-note-id='$this->photo_id' id='business$this->photo_id'>软广</a>";
                }
                if ($this->display_business) {
                    $displayBusiness = "<a href='javascript:;' class='btn btn-success addDisplayBusiness'  data-note-id='$this->photo_id' id='display$this->photo_id'>商业硬广</a>";
                } else {
                    $displayBusiness = "<a href='javascript:;' class='btn btn-default addDisplayBusiness'  data-note-id='$this->photo_id' id='display$this->photo_id'>商业硬广</a>";
                }

                if ($like_btn) {
                    return $detail . $log . "<br><br>" . $like_btn . "<br><br>" . $businessBtn . "<br><br>" . $displayBusiness . "<br><br>" . $copy_btn;
                }
                return $detail . $log . "<br><br>" . $businessBtn . "<br><br>" . $displayBusiness . "<br><br>" . $copy_btn;

                if ($like_btn) {
                    return $detail . $log . "<br><br>" . $like_btn . "<br><br>" . $businessBtn . "<br><br>" . $copy_btn;
                }
                return $detail . $log . "<br><br>" . $businessBtn . "<br><br>" . $copy_btn;
            })->width(150);
            $grid->column('remark', '图说')->display(function () {
                $s2 = preg_replace("/#.*?\s/", '', $this->remark . $this->title);
                $s3 = preg_replace("/\\[.*?]/", '', $s2);
                $s4 = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", strip_tags($s3));
                return "<strong>[字数]: </strong>" .
                    mb_strlen($s4) . "<br><strong>[标题]:</strong>{$this->title}<br><strong>[正文]:</strong><br>" . nl2br($this->remark);
            })->width(350);

            $grid->column('relation', '关联信息')->display(function () {
                $addtime = date('Y-m-d H:i:s', $this->addtime);
                if ($this->type == dbPhoto::TYPE_DIARY) {
                    return "内容主体：装修日记 <br> 日记id：{$this->task_id} <br>发布时间：{$addtime}";
                } else if ($this->type == dbPhoto::TYPE_CIRCLE) {
                    return "内容主体：圈子内容 <br> 圈子id：{$this->task_id} <br> 圈子名称：{$this->name} <br>发布时间：{$addtime}";
                } else {
                    return "内容主体：图片<br>发布时间：$addtime";
                }
            })->width(150);
            $grid->column('admin_score', '打分')->display(function () {
                // primary
                $class_normal = 'btn-defalut';
                $class_great = 'btn-defalut';
                $class_bad = 'btn-defalut';
                $class_best = 'btn-defalut';
                $common = $this->machine_recognition ? 'btn-primary' : 'btn-success';
                if ($this->admin_score <= 30 && $this->admin_score > 20) {
                    $class_normal = $common;
                } else if ($this->admin_score > 30 && $this->admin_score < 80) {
                    $class_great = $common;
                } else if ($this->admin_score < 6 && $this->admin_score > 0) {
                    $class_bad = $common;
                } else if ($this->admin_score >= 80) {
                    $class_best = $common;
                }
                $options_normal = "<button class='btn normal grade $class_normal btn' data-detail_id= '$this->detail_id'  data-note-id='$this->photo_id' data-score='30' data-quality='" . dbPhoto::QUALITY_ORDINARY . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_ORDINARY] . "</button><br><br>";
                $options_great = "<button class='btn great grade $class_great' data-detail_id='$this->detail_id'  data-note-id='$this->photo_id' data-score='70' data-quality='" . dbPhoto::QUALITY_HIGH . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_HIGH] . "</button><br><br>";
                $options_best = "<button class='btn best grade $class_best' data-detail_id= '$this->detail_id'  data-note-id='$this->photo_id' data-score='80' data-quality='" . dbPhoto::QUALITY_FEATURED . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_FEATURED] . "</button><br><br>";
                $userInfo = $this->user_info;
                if ($userInfo['type'] != Member::AUTH_USER_DESIGNER && $userInfo['type'] != Member::AUTH_USER_UNAUTH_DESIGNER) {
                    $options_great = "<button class='btn great grade $class_great addLike' data-detail_id= '$this->detail_id'  data-note-id='$this->photo_id' data-score='70' data-quality='" . dbPhoto::QUALITY_HIGH . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_HIGH] . "</button><br><br>";
                    $options_best = "<button class='btn best grade $class_best addLike' data-detail_id= '$this->detail_id'  data-note-id='$this->photo_id' data-score='80' data-quality='" . dbPhoto::QUALITY_FEATURED . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_FEATURED] . "</button><br><br>";
                }
                $options_bad = "<button class='btn bad $class_bad' data-detail_id= '$this->detail_id'   data-note-id='$this->photo_id' data-score='5' data-quality='" . dbPhoto::QUALITY_LOW . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_LOW] . "</button>";

                return $options_normal . $options_great . $options_best . $options_bad;
            });


            $grid->column('category', '品类')->display(function () use ($categoryLabelAll) {
                $optionsFirst = "<p style='display: flex; align-items: center'>一级品类：<span class='un_category' style='height: 18px; width: 18px; text-align: center; line-height: 15px; display: inline-block; cursor: pointer; border-radius: 100%; color: #fff; background-color: #ccc' data-id={$this->photo_id} >x</span></p>";
                $optionsSecondStr = empty($this->category_second) ? '' : '二级品类：';
                $optionsSecond = '<div><p class="category_second_p">' . $optionsSecondStr . '</p><div class="category_second_lable" style="margin-top: 10px">';
                foreach ($categoryLabelAll as $val) {
                    $btn = $this->category_source == 1 ? 'btn-twitter' : 'btn-success';
                    //一级分类组装
                    if ($val['level'] == 1) {
                        $class_success = ($val['id'] == $this->category_first) ? $btn : 'btn-default';
                        $optionsFirst = $optionsFirst . "<button style='display:inline-block;margin:2px;' class='community_category_first btn btn-sm $class_success' data-detail_id= '$this->detail_id'  data-id='$this->photo_id' data-category-first-id='" . $val['id'] . "' data-category-second-id='" . $this->category_second . "' >" . $val['name'] . "</button>&nbsp;";
                    }
                    //一级分类组装
                    if ($val['p_id'] == $this->category_first && $val['p_id'] != 0) {
                        $class_success = ($val['id'] == $this->category_second) ? $btn : 'btn-default';
                        $optionsSecond = $optionsSecond . "<button style='display:inline-block;margin:2px;' class='community_category_second btn btn-sm $class_success' data-detail_id= '$this->detail_id' data-id='$this->photo_id' data-category-second_id='" . $val['id'] . "' >" . $val['name'] . "</button>&nbsp;";
                    }
                }
                $optionsSecond .= '</div></div>';
                return $optionsFirst . $optionsSecond;
            });
        });

        Admin::script($this->RecheckGradeScript());
        Admin::script($this->lowScoreScript());
//        Admin::script($this->markScript());
//        Admin::script($this->imgScript());
        Admin::script($this->adminLike());
        Admin::script(ContentCategory::clickCategoryScript());
        Admin::script(self::RecheckClickCategoryLableScript(Admin::user()->id));
        Admin::script($this->adminCopy());

        return $content
            ->row(function (Row $row) use($aTaskInfo){
                $row->column(9,"<html><span>任务内容量：".$aTaskInfo['task_num']."</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span>已经复审内容量：".$aTaskInfo['check_num'] ."</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>截止时间：".$aTaskInfo['plant_execution_end_time']."</span></html> ");
            })
            ->header('任务复审')
            ->breadcrumb(['text' => '复审&质检','url'=>'/photo/photorecheckquality/index'],
                ['text' => '详情'])
            ->description( $aTaskInfo['task_name'])
            ->body($listGrid);

    }


    /**
     * 任务复审列表
     */
    public function checkTaskIndex(Request $request, Content $content)
    {
        $params = $request->all();
        $sIsDiff = $params['is_diff'] ?? '';
        $iTaskId = $params['task_id'];

        $aTaskInfo = RecheckQualityTask::getById($iTaskId);
        $aTaskInfo['use_time'] = '未知';
        if($aTaskInfo['check_start_time']!='0000-00-00 00:00:00' && $aTaskInfo['check_end_time'] !='0000-00-00 00:00:00'){
            $enddate = $aTaskInfo['check_end_time'];
            $startdate = $aTaskInfo['check_start_time'];
            $date=floor((strtotime($enddate)-strtotime($startdate))/86400);

            $hour=floor((strtotime($enddate)-strtotime($startdate))%86400/3600);

            $minute=floor((strtotime($enddate)-strtotime($startdate))%86400%3600/60);

            $second=floor((strtotime($enddate)-strtotime($startdate))%86400%60);
            $aTaskInfo['use_time'] = $date ."天".$hour."小时".$minute."分钟".$second."秒";

        }
        $aTaskInfo['finish_status'] = '正常';
        if($aTaskInfo['check_end_time'] > $aTaskInfo['plant_execution_end_time']){
            $aTaskInfo['finish_status'] = '超时';
        }

        //已经审核任务任务量
        $aTaskInfo['check_num'] = self::getIscheckNum($iTaskId);

        $unCheckNum = $aTaskInfo['task_num'] -  $aTaskInfo['check_num'] ;




        //审核异常数据量
        $isDiffCheckWhere = [
            'task_id' => $iTaskId,
            'is_check' => 1,
            'is_diff' => 2,
        ];
        $isDiffCheckNum = RecheckQualityDetail::getCount($isDiffCheckWhere);
        if($unCheckNum == 0 &&$isDiffCheckNum ==0){
            $aTaskInfo['scale'] = 0;
        }else{
            $aTaskInfo['scale'] = bcdiv(($unCheckNum+$isDiffCheckNum),$aTaskInfo['task_num'],2)*100;
        }

        $aTaskInfo['diff_num'] =$unCheckNum+$isDiffCheckNum;


        $aWhere['task_id'] = $iTaskId;
        $aWhere['ORDER'] = ['id' => 'DESC'];
        if(in_array($sIsDiff, [1, 2,3])){
            $aWhere['is_diff'] = $sIsDiff;
        }
        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $aTaskDetailList = sRecheckQualityDetail::getList($page, $pageSize, $aWhere);
        $total = $aTaskDetailList['total'];
        $ids = array_column($aTaskDetailList['list'],'obj_id');

        $photos = Photos::getPhotos($ids); // 通过id获取图片信息
        // 获取装修日记
        $diaryList = $diaryIds = $circleList = $circleIds = [];
        foreach ($photos as $photo) {
            if ($photo['type'] == dbPhoto::TYPE_DIARY) {
                $diaryIds[] = $photo['id'];
            }
            if ($photo['type'] == dbPhoto::TYPE_CIRCLE) {
                $circleIds[] = $photo['id'];
            }
        }

        if ($diaryIds) {
            $diaryList = Read::getDiaryByDiaryIds($diaryIds);
        }
        if ($circleIds) {
            $circleList = PhotosCircle::selectPhotoCircle($circleIds);
        }

        //用户信息
        $uids = empty($photos) ? [] : array_column($photos, 'uid');
        $user_infos = Member::getUserInfoByIds($uids);
        $user_infos_regular = [];
        if ($user_infos && is_array($user_infos)) {
            foreach ($user_infos as $user_info) {
                $user_infos_regular[$user_info['uid']] = $user_info;
            }
        }

        //用户等级信息
        $user_levels = UserPortrait::getUserLevelByUIds(array_values(array_unique($uids)));
        //特征信息
        $features = AdmNoteFeature::getFeatureByIds($ids);
        $features_arr = [];
        if ($features && is_array($features)) {
            foreach ($features as $features_info) {
                $features_arr[$features_info['note_id']][] = $features_info['feature'];
            }
        }
        $features_regular = [];
        if ($features_arr && is_array($features_arr)) {
            foreach ($features_arr as $note_id => $feature) {
                $features_regular[$note_id] = implode(',', $feature);
                $features_regular[$note_id] = array_unique(explode(',', $features_regular[$note_id]));
                $features_regular[$note_id] = implode(',', $features_regular[$note_id]);
            }
        }

        $admin_likes = [];
        $likes = AdminAccountOperate::getByObjIds($ids, AdminAccountOperate::ACCOUNT_TYPE_LIKE);
        if ($likes && is_array($likes)) {
            foreach ($likes as $like) {
                $admin_likes[$like['obj_id']] = (string)Admin::user()->find($like['admin_id'])->name;
            }
        }

        //获取社区特征分类
        $categoryList = sContentRelatedCategory::getTypesByObjIds($ids);
        $categoryLabelAll = mContentCategoryLabel::getListFormatKey(0, 0, 0);
        // 获取note关联的wiki
        $wiki_map = Photos::getWikiListMapByIds($ids);
        //获取扩展信息
        $extend_map = [];
        $extend_info = PhotosExtend::getExtendInfoByNoteIds($ids);
        if ($extend_info && is_array($extend_info)) {
            foreach ($extend_info as $value) {
                $extend_map[$value['obj_id']] = $value;
            }
        }
        if ($ids) {
            $machineQuality = cMachineQuality::getItems($ids); // 获取机器打分信息
        }

        $i = 1;
        foreach ($photos as &$info) {
            $info['photo_id'] = $info['id'];
            $categoryFirstId = 0;
            $categorySecondId = 0;
            $categorySource = 2;
            if (isset($categoryList[$info['photo_id']])) {
                $cateInfo = $categoryList[$info['photo_id']];
                $categoryFirstField = 'category_first_id';
                $categorySecondField = 'category_second_id';
                if ($cateInfo['source'] == 1) {//机器
                    $categoryFirstField = 'machine_category_first_id';
                    $categorySecondField = 'machine_category_second_id';
                    $categorySource = 1;
                }
                $categoryFirstId = $categoryList[$info['photo_id']][$categoryFirstField];
                $categorySecondId = $categoryList[$info['photo_id']][$categorySecondField];
            }

            $info['id'] = $i;
            $info['user_info'] = $user_infos_regular[$info['uid']];
            $info['admin_like'] = (string)$admin_likes[$info['photo_id']];
            $info['remark'] =  $this->highLight($info['remark']);
            $info['features'] = $features_regular[$info['photo_id']];
            $info['user_levels'] = $user_levels[$info['uid']];
            $info['category_first'] = $categoryFirstId;
            $info['category_second'] = $categorySecondId;
            $info['category_source'] = $categorySource;
            if ($info['show_type'] == DbPhotos::SHOW_TYPE_VIDEO) {
                $videoInfo = sVideos::getVideoCoverInfoById($info['video_id']);
                $info['expand'] = $this->_getVideoExpand($videoInfo, $wiki_map[$info['photo_id']]['list']);
            } else {
                $picInfos = json_decode($info['pic_list'], true) ?: [];
                $info['expand'] = $this->_getPicExpand($picInfos, $wiki_map[$info['photo_id']]['list']);
            }
            $info['expand'] .= $this->_getDivLine();
            if ($info['type'] == dbPhoto::TYPE_DIARY) {
                $info['title'] = !empty($info['title']) ? $info['title'] . "---". $diaryList[$info['photo_id']]['title'] : $diaryList[$info['photo_id']]['title'];
                $info['task_id'] = $diaryList[$info['photo_id']]['task_id'];
            }
            if ($info['type'] == dbPhoto::TYPE_CIRCLE) {
                $info['name'] = $circleList[$info['photo_id']]['circle_name'];
                $info['task_id'] = $circleList[$info['photo_id']]['circle_id'];
            }
            $info['is_business'] = $extend_map[$info['photo_id']]['is_business'] ?: 0;
            $info['display_business'] = $extend_map[$info['photo_id']]['is_display_business'] ?: 0;
            $info['machine_recognition'] = $machineQuality[$info['photo_id']]??0;
            $i++;
        }

        $options = [
            'perPage' => $request->input('per_page') ?: 20
        ];

        $gridModel = new pGridDataModel($photos, $total, $options);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($categoryLabelAll,$aTaskInfo) {

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();
//            $grid->disableFilter();


            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->filter(function ($filter) {
                $filter->disableIdFilter();
                $filter->column(1/2, function ($filter){
                    $filter->equal('is_diff', '是否存在差异')->radio(RecheckQualityDetail::IS_DIFF);
                });
            });

            $grid->column('photo_id', 'NOTE_ID')->expand(function () {
                return $this->expand;
            }, true)->width(90);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('admin_like', '额外信息')->display(function () {
                $userInfo = $this->user_info;
                if ($userInfo['type'] != Member::AUTH_USER_DESIGNER && $userInfo['type'] != Member::AUTH_USER_UNAUTH_DESIGNER) {
                    if (empty($this->admin_like)) {
                        $like_btn = "<a href='javascript:;' class='btn btn-default addLike'  data-note-id='$this->photo_id' id='like$this->photo_id'>点赞</a>";
                    } else {
                        $like_btn = "<a href='javascript:;' class='btn btn-success'  data-note-id='$this->photo_id' id='like$this->photo_id'>$this->admin_like 已赞</a>";
                    }
                }
                $detail = "<a href='http://manage.haohaozhu.me/Admin/Photos/detail/photo_id/$this->photo_id' target='_blank' >图片详情</a><br>";
                $log = "<a href='/admin/photo/photoAuditLog?&id=$this->photo_id' target='_blank' >审核日志</a><br>";
                $copy_btn = "<a href='javascript:;' class='btn btn-default copyH5'  data-id='$this->photo_id' >复制链接</a>";
                // 一部分员工，是兼职，但又得有正式员工的权限
                if (Admin::user()->isRole('partime.user') && !Admin::user()->can('part_time.business')) {
                    if ($like_btn) {
                        return $detail . $log . $like_btn . "<br><br>" . $copy_btn;
                    }
                    return $detail . $log . "<br><br>" . $copy_btn;
                }
                if ($this->is_business) {
                    $businessBtn = "<a href='javascript:;' class='btn btn-success addBusiness'  data-note-id='$this->photo_id' id='business$this->photo_id'>软广</a>";
                } else {
                    $businessBtn = "<a href='javascript:;' class='btn btn-default addBusiness'  data-note-id='$this->photo_id' id='business$this->photo_id'>软广</a>";
                }
                if ($this->display_business) {
                    $displayBusiness = "<a href='javascript:;' class='btn btn-success addDisplayBusiness'  data-note-id='$this->photo_id' id='display$this->photo_id'>商业硬广</a>";
                } else {
                    $displayBusiness = "<a href='javascript:;' class='btn btn-default addDisplayBusiness'  data-note-id='$this->photo_id' id='display$this->photo_id'>商业硬广</a>";
                }

                if ($like_btn) {
                    return $detail . $log . "<br><br>" . $like_btn . "<br><br>" . $businessBtn . "<br><br>" . $displayBusiness . "<br><br>" . $copy_btn;
                }
                return $detail . $log . "<br><br>" . $businessBtn . "<br><br>" . $displayBusiness . "<br><br>" . $copy_btn;

                if ($like_btn) {
                    return $detail . $log . "<br><br>" . $like_btn . "<br><br>" . $businessBtn . "<br><br>" . $copy_btn;
                }
                return $detail . $log . "<br><br>" . $businessBtn . "<br><br>" . $copy_btn;
            })->width(150);
            $grid->column('remark', '图说')->display(function () {
                $s2 = preg_replace("/#.*?\s/", '', $this->remark . $this->title);
                $s3 = preg_replace("/\\[.*?]/", '', $s2);
                $s4 = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", strip_tags($s3));
                return "<strong>[字数]: </strong>" .
                    mb_strlen($s4) . "<br><strong>[标题]:</strong>{$this->title}<br><strong>[正文]:</strong><br>" . nl2br($this->remark);
            })->width(350);

            $grid->column('relation', '关联信息')->display(function () {
                $addtime = date('Y-m-d H:i:s', $this->addtime);
                if ($this->type == dbPhoto::TYPE_DIARY) {
                    return "内容主体：装修日记 <br> 日记id：{$this->task_id} <br>发布时间：{$addtime}";
                } else if ($this->type == dbPhoto::TYPE_CIRCLE) {
                    return "内容主体：圈子内容 <br> 圈子id：{$this->task_id} <br> 圈子名称：{$this->name} <br>发布时间：{$addtime}";
                } else {
                    return "内容主体：图片<br>发布时间：$addtime";
                }
            })->width(150);
            $grid->column('admin_score', '打分')->display(function () {
                // primary
                $class_normal = 'btn-defalut';
                $class_great = 'btn-defalut';
                $class_bad = 'btn-defalut';
                $class_best = 'btn-defalut';
                $common = $this->machine_recognition ? 'btn-primary' : 'btn-success';
                if ($this->admin_score <= 30 && $this->admin_score > 20) {
                    $class_normal = $common;
                } else if ($this->admin_score > 30 && $this->admin_score < 80) {
                    $class_great = $common;
                } else if ($this->admin_score < 6 && $this->admin_score > 0) {
                    $class_bad = $common;
                } else if ($this->admin_score >= 80) {
                    $class_best = $common;
                }
                $options_normal = "<button class='btn normal grade $class_normal btn' data-note-id='$this->photo_id' data-score='30' data-quality='" . dbPhoto::QUALITY_ORDINARY . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_ORDINARY] . "</button><br><br>";
                $options_great = "<button class='btn great grade $class_great' data-note-id='$this->photo_id' data-score='70' data-quality='" . dbPhoto::QUALITY_HIGH . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_HIGH] . "</button><br><br>";
                $options_best = "<button class='btn best grade $class_best' data-note-id='$this->photo_id' data-score='80' data-quality='" . dbPhoto::QUALITY_FEATURED . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_FEATURED] . "</button><br><br>";
                $userInfo = $this->user_info;
                if ($userInfo['type'] != Member::AUTH_USER_DESIGNER && $userInfo['type'] != Member::AUTH_USER_UNAUTH_DESIGNER) {
                    $options_great = "<button class='btn great grade $class_great addLike' data-note-id='$this->photo_id' data-score='70' data-quality='" . dbPhoto::QUALITY_HIGH . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_HIGH] . "</button><br><br>";
                    $options_best = "<button class='btn best grade $class_best addLike' data-note-id='$this->photo_id' data-score='80' data-quality='" . dbPhoto::QUALITY_FEATURED . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_FEATURED] . "</button><br><br>";
                }
                $options_bad = "<button class='btn bad $class_bad' data-note-id='$this->photo_id' data-score='5' data-quality='" . dbPhoto::QUALITY_LOW . "'>" . dbPhoto::QUALITY_DESC[dbPhoto::QUALITY_LOW] . "</button>";

                return $options_normal . $options_great . $options_best . $options_bad;
            });


            $grid->column('category', '品类')->display(function () use ($categoryLabelAll) {
                $optionsFirst = "<p style='display: flex; align-items: center'>一级品类：<span class='un_category' style='height: 18px; width: 18px; text-align: center; line-height: 15px; display: inline-block; cursor: pointer; border-radius: 100%; color: #fff; background-color: #ccc' data-id={$this->photo_id} >x</span></p>";
                $optionsSecondStr = empty($this->category_second) ? '' : '二级品类：';
                $optionsSecond = '<div><p class="category_second_p">' . $optionsSecondStr . '</p><div class="category_second_lable" style="margin-top: 10px">';
                foreach ($categoryLabelAll as $val) {
                    $btn = $this->category_source == 1 ? 'btn-twitter' : 'btn-success';
                    //一级分类组装
                    if ($val['level'] == 1) {
                        $class_success = ($val['id'] == $this->category_first) ? $btn : 'btn-default';
                        $optionsFirst = $optionsFirst . "<button style='display:inline-block;margin:2px;' class='community_category_first btn btn-sm $class_success' data-id='$this->photo_id' data-category-first-id='" . $val['id'] . "' data-category-second-id='" . $this->category_second . "' >" . $val['name'] . "</button>&nbsp;";
                    }
                    //一级分类组装
                    if ($val['p_id'] == $this->category_first && $val['p_id'] != 0) {
                        $class_success = ($val['id'] == $this->category_second) ? $btn : 'btn-default';
                        $optionsSecond = $optionsSecond . "<button style='display:inline-block;margin:2px;' class='community_category_second btn btn-sm $class_success' data-id='$this->photo_id' data-category-second_id='" . $val['id'] . "' >" . $val['name'] . "</button>&nbsp;";
                    }
                }
                $optionsSecond .= '</div></div>';
                return $optionsFirst . $optionsSecond;
            });
        });

        Admin::script($this->gradeScript());
        Admin::script($this->lowScoreScript());
        Admin::script($this->adminLike());
        Admin::script(ContentCategory::clickCategoryScript());
        Admin::script(ContentCategory::clickCategoryLableScript(Admin::user()->id));
        Admin::script($this->adminCopy());

        return $content
            ->row(function (Row $row) use($aTaskInfo){
                $row->column(10, "<html>
<p><span>任务名称：".$aTaskInfo['task_name']."</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>任务提交时间：".$aTaskInfo['check_end_time']."( ".$aTaskInfo['finish_status'] .")"."</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>总耗时：".$aTaskInfo['use_time'] ."</span></p>
<p><span>任务内容量：".$aTaskInfo['task_num']."<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>复审内容量：".$aTaskInfo['check_num']."</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>复审结果差异率：".$aTaskInfo['scale']."%</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>复审差异值：".$aTaskInfo['diff_num']."</span></p></html>");
            })
            ->header('任务质检')
            ->breadcrumb(['text' => '复审&质检','url'=>'/photo/photorecheckquality/index'],
                ['text' => '详情'])
            ->description( $aTaskInfo['task_name'])
            ->body($listGrid);

    }

    /**
     * 获取已经审核完成的数据量
     */
    public static function getIscheckNum($iTaskId){
        //已经审核任务任务量
        $unCheckWhere = [
            'task_id' => $iTaskId,
            'is_check' => 1,
        ];
        return RecheckQualityDetail::getCount($unCheckWhere);
    }

    /**
     * 通过条件搜索获取数据
     */
    public static function getSearchResult($request)
    {
        if (HhzEnv::isProduction() || HhzEnv::isGray()) {
            return SearchFilter::getSearchResultByParams($request);
        }

        if (HhzEnv::isTest()) {
            return  [
                'rows'=>[
                    '0009wlb0000boo1x',
                    '0009wfm0000boo1x',
                    '0009wfl0000boo1x',
                    '0009wfk0000boo1x',
                    '0009wfj0000boo1x',
                    '0009wfi0000boo1x',
                    '0009wfc0000boo1x',
                    '0009wf80000boo1x',
                    '0009uxm0000boo1x',
                    '0009vci0000boo1x',
                    ],
                'total'=>10];
        } else{
            return  ['rows'=>['0009wfb0000boo1x'],'total'=>1];
        }
    }

    /**
     * 将符合条件的数据写入新新表
     */
    public static function setNotesToDetail($request,$iTaskId,$iTaskNum)
    {
        $request->merge(['per_page' => $iTaskNum]);
        $searchResult = self::getSearchResult($request);
        $aAllids = $searchResult['rows'];

        if($iTaskNum == 1){
            shuffle($aAllids);
            $ids[]  = array_pop($aAllids);
        }else if($iTaskNum == $searchResult['rows']){
            $ids[] = $aAllids;
        }else{
            shuffle($aAllids);
            $ids =  array_slice( $aAllids,0,$iTaskNum);
        }

        $photos = Photos::getPhotos($ids); // 通过id获取图片信息
        //获取社区特征分类
        $categoryList = sContentRelatedCategory::getTypesByObjIds($ids);

        foreach ($photos as $info) {
            $aDetail = [];
            $aDetail['task_id'] = $iTaskId;
            $aDetail['obj_id'] = $info['id'];
            $info['photo_id'] = $info['id'];
            $categorySecondId = 0;
            if (isset($categoryList[$info['photo_id']])) {
                $cateInfo = $categoryList[$info['photo_id']];
                $categorySecondField = 'category_second_id';
                if ($cateInfo['source'] == 1) {//机器
                    $categorySecondField = 'machine_category_second_id';
                }
                $categorySecondId = $categoryList[$info['photo_id']][$categorySecondField];
            }

            $aDetail['origin_category_second_id'] = $categorySecondId;
            $aDetail['score'] =  $info['admin_score'];
            $aDetailList[] = $aDetail;
        }
        if(!empty($aDetailList)){
            $res = RecheckQualityDetail::add($aDetailList);
        }
        if($res){
            return true;
        }
        return false;
    }


    /**
     * 以下是复制过来的方法（部分url有修改）
     */
    // 正文中轻话题高亮
    private function highLight($remark)
    {
        preg_match_all('/#([\w\-]{1,15}+)/u', $remark . ' ', $userTags);

        if (isset($userTags[0]) && !empty($userTags[0])) {
            $replaceRemarkArr = [];
            foreach ($userTags[0] as $userTag) {
                $replaceRemarkArr[] = '<b style="color:deepskyblue;">' . $userTag . '</b>';
            }
            return str_replace($userTags[0], $replaceRemarkArr, $remark);
        }

        return $remark;
    }

    private function _getPicExpand($picInfos, $wikiInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($picInfo) {
            $imgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picInfo['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            return "<img class='img-responsive float-left center-block col-md-2 img' src='{$imgUrl}' />";
        }, (array)$picInfos)));
        $box = new Box('图片信息' . '  (数量:' . count($picInfos) . ')');
        $box->solid()->content($row->render());
        return $box->render() . ($wikiInfos ? $this->_getWikiExpand($wikiInfos) : '');
    }

    /**
     * 分割线
     * @return string
     */
    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }

    /**
     * 复审打分操作
     */
    private function RecheckGradeScript()
    {
        $url = route('photorecheckquality.rechecksetGrade');
        return <<<SCRIPT
            $('.grade').click(function() {
                $(this).addClass('btn-success');
                $(this).siblings('button').removeClass('btn-success');
                $(this).siblings('button').removeClass('btn-primary');
                $(this).siblings('button').addClass('btn-default');
                toastr.success('打分成功', null, {
                    timeOut : 1000
                });
                
                let detailId = $(this).data('detail_id');
                let noteId = $(this).data('note-id');
                let score = $(this).data('score');
                let quality = $(this).data('quality');
                let url = '{$url}'
                let params = {detail_id:detailId,note_id:noteId, score:score, quality:quality}
                $.post(url, params)
            });

SCRIPT;
    }
    /**
     * 质检打分操作
     */
    private function gradeScript()
    {
        $url = route('photocheck.grade');
        return <<<SCRIPT
            $('.grade').click(function() {
                $(this).addClass('btn-success');
                $(this).siblings('button').removeClass('btn-success');
                $(this).siblings('button').removeClass('btn-primary');
                $(this).siblings('button').addClass('btn-default');
                toastr.success('打分成功', null, {
                    timeOut : 1000
                });

                let noteId = $(this).data('note-id');
                let score = $(this).data('score');
                let quality = $(this).data('quality');
                let url = '{$url}'
                let params = {note_id:noteId, score:score, quality:quality}
                $.post(url, params)
            });

SCRIPT;
    }

    private function lowScoreScript()
    {
        return <<<SCRIPT
            $('.bad').unbind('click').click(function() {
                var _this = $(this);
                var note_id = $(this).data('note-id');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '原因归类',
                    shadeClose: true,
                    shade: 0.9,
                    area: ['700px', '600px'],
                    content: '/admin/photo/photocheck/lowScore/'+note_id,
                    end: function() {
                         $.ajax({type:"get",url:"/admin/photo/photocheck/poorQuality/"+note_id,success:function(code) {
                            if(code == 1) {
                                _this.addClass('btn-success');
                                _this.siblings('button').removeClass('btn-success');
                                _this.siblings('button').addClass('btn-default');
                            }
                        }})
                    }
                });
		    });
SCRIPT;
    }

    //运营点赞
    public function adminLike()
    {
        return <<<SCRIPT
            $('.addLike').click(function() {
                var note_id = $(this).data('note-id');
                $.ajax({type:"get",url:"/admin/photo/photocheck/like/"+note_id,success:function(data){
                    if(data != '') {
                        $('#like'+note_id).html(data+"已点赞");
                        $('#like'+note_id).addClass('btn-success');
                        $('#like'+note_id).css('color','#FFFFFF');
                        $('#like'+note_id).attr('disabled', 'disabled');
                    }
                }});
            });
            
             $('.addDisplayBusiness').click(function() {
                var note_id = $(this).data('note-id');
                console.log($(this).hasClass('addDisplayBusiness'));
                if($(this).hasClass('btn-success')) {
                    type = 'remove';
                } else {
                    type = 'add';
                }
                $.ajax({type:"get",url:"/admin/photo/photocheck/displayBusiness/"+note_id+"/"+type,success:function(data){
                    if(data) {
                    console.log(type)
                       if (type == 'remove'){
                            $('#display'+note_id).removeClass('btn-success');
                            $('#display'+note_id).addClass('btn-default');
                            $('#display'+note_id).css('color','#444');                        
                       }else{
                        $('#display'+note_id).addClass('btn-success');
                        $('#display'+note_id).css('color','#FFFFFF');
                       } 
                         toastr.success('修改成功', null, {
                            timeOut : 1000
                        });  
                    }else{
                     toastr.success('修改失败', null, {
                            timeOut : 1000
                        });
                      }
             }});
            });  
            
            $('.addBusiness').click(function() {
                var note_id = $(this).data('note-id');
                console.log($(this).hasClass('addBusiness'));
                 if($(this).hasClass('btn-success')) {
                    type = 'remove';
                } else {
                    type = 'add';
                }
                $.ajax({type:"get",url:"/admin/photo/photocheck/business/"+note_id+"/"+type,success:function(data){
                    if(data) {
                       if (type == 'remove'){
                            $('#business'+note_id).removeClass('btn-success');
                            $('#business'+note_id).addClass('btn-default');
                            $('#business'+note_id).css('color','#444');                        
                       }else{
                        $('#business'+note_id).addClass('btn-success');
                        $('#business'+note_id).css('color','#FFFFFF');
                       } 
                         toastr.success('修改成功', null, {
                            timeOut : 1000
                        });  
                    }else{
                     toastr.success('修改失败', null, {
                            timeOut : 1000
                        });
                    }
                }});
            });          
SCRIPT;
    }

    //复制H5链接
    public function copyUrl($id)
    {
        return Hhzurl::h5PhotoShow($id);
    }

    public function adminCopy()
    {
        return <<<SCRIPT
        $('.copyH5').click(function() {
            var id = $(this).data('id');
            $.ajax({type:"get",url:"/admin/photo/photocheck/copy/"+id,success:function(url){
            var tempInput = document.createElement("input");
            tempInput.value = url;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand("copy");
            document.body.removeChild(tempInput);
            }});
        });
SCRIPT;
    }

    //品类操作
    public static function RecheckClickCategoryLableScript($adminId)
    {
        return <<<SCRIPT
            $('.community_category_first').click(function() {
                var _this = $(this);
                let obj_id = $(this).data('id');
                let detail_id = $(this).data('detail_id');
                let community_category_first_id = $(this).data('category-first-id');
                let url = '/admin/photo/photocheck/index/getCategoryLabelById?q='+community_category_first_id+'&obj_id='+obj_id;
                $.get(url, function (result) {
                    let data = result.list;
                    var html = '';
                    $.each(data, function(i,val){     
                        var name = val.text;
                        var id = val.id;
                        var btn = 'btn-default';
                        _this.addClass("btn-success").siblings().removeClass("btn-success")
                        _this.addClass("btn-success").siblings().removeClass("btn-twitter")
                        if(id == result.obj_info.category_second_id){
                            html += "<button style='display:inline-block;margin:2px;' class='community_category_second btn btn-sm btn-success' data-detail_id='"+detail_id+"' data-id='"+obj_id+"' data-category-second_id='"+ id +"' >"+ name +"</button>&nbsp;"
                        } else {
                            html += "<button style='display:inline-block;margin:2px;' class='community_category_second btn btn-sm btn-default' data-detail_id='"+detail_id+"' data-id='"+obj_id+"' data-category-second_id='"+ id +"' >"+ name +"</button>&nbsp;"
                        }
                    });
                    _this.parent(".column-category").find(".category_second_lable").html(html);
                    $(".category_second_p").text("二级品类")
                });  
               
            });
            let isclick = false
            $('body').unbind('click').on( "click", '.community_category_second', function(e){
                if(!isclick){
                    isclick = true
                    var _this = $(this);
                    let detail_id = _this.data('detail_id');
                    let obj_id = _this.data('id');
                    let second_id = _this.data('category-second_id');
                    let params = {detail_id:detail_id,obj_id:obj_id,second_id:second_id,admin_id:$adminId};
                    let url = '/admin/photo/photorecheckquality/index/changeContentCategoryLabel';
                    _this.addClass("btn-success").siblings().removeClass("btn-success")
                    _this.addClass("btn-success").siblings().removeClass("btn-twitter")
                    $.post(url, params, function (e) {
                        if(e.code == 1){
                        _this.parent(".category_second_lable").siblings(".content-category-second").attr('data-category-second-id', second_id);
                          toastr.success(e.msg, '操作成功', {
                                timeOut : 1000
                            }); 
                        }else{
                            toastr.error(e.msg, '操作失败', {
                                timeOut : 1000
                            });
                        }
                        isclick = false;
                    });
                }
            });
            $('.un_category').click(function() {
                var _this = $(this);
                let obj_id = $(this).data('id');
                let url = '/admin/photo/photocheck/index/resetContentCategory';
                let params = {
                    obj_id:obj_id
                };
               $.post(url, params , function (result) {              
                         if (result.code == 0){
                            layer.msg('取消失败，请刷新页面重试');                              
                        } else {
                            layer.msg('操作成功');
                            _this.parents(".column-category").find("button").removeClass("btn-success")
                        }
                    });
            });
SCRIPT;
    }

    /**
     * 复审修改品类
     */
    public function changeContentCategoryLabel(Request $request)
    {
        $request = $request->all();
        $iDetailId = $request['detail_id'];
        if (empty($iDetailId)) return '缺少任务详情id';

        $secondId = $request['second_id'] ?? 0;
        $objId = $request['obj_id'] ?? 0;
        $adminId = $request['admin_id'] ?? 0;

        /** 比较差异 */
        $aDetailInfo =  RecheckQualityDetail::getById($iDetailId);
        $aData['category_check'] = RecheckQualityDetail::CHECKED;
        $aData['admin_id'] = Admin::user()->name;
        $aData['check_time'] = date('Y-m-d H:i:s');
        if($aDetailInfo['score_check'] == RecheckQualityDetail::CHECKED){
            $aData['is_check'] = RecheckQualityDetail::CHECKED;
        }
        if($aDetailInfo['origin_category_second_id'] != $secondId){
            $aData['is_diff'] = RecheckQualityDetail::ISDIFF;
        }else{
            $aData['is_diff'] = RecheckQualityDetail::SAME;
        }
        RecheckQualityDetail::updateById($iDetailId,$aData);

        $firstId = mContentCategoryLabel::getDetailById($secondId)['p_id'] ?? 0;
        if (empty($firstId)) return '缺少一级品类ID';
        $code = sContentRelatedCategory::changeNoteCategory($objId, $firstId, $secondId, $adminId, mContentRelatedCategory::SOURCE_ADMIN);
        $result = ['code' => $code];
        return response()->json($result);
    }

    /**
     * 复审打分操作
     */
    public function rechecksetGrade(Request $request)
    {
        $code = 1;
        try {
            $params = $request->all();
            $note_id = $params['note_id'];
            $source = $params['source'];
            $iDetailId = $params['detail_id'];
            $data = [
                'quality' => $params['quality'],
                'admin_score' => $params['score'],
                'show_status' => dbPhoto::SHOW_STATUS_NORMAL,
                'status' => dbPhoto::STATUS_SUCCESS
            ];

            // 查询更新之前此note的质量
            $photoInfo = Photos::getPhoto($note_id);
            $qualityLastTime = -1;
            if ($photoInfo['quality'] != $params['quality']) {
                $qualityLastTime = $photoInfo['quality'];
            }


            /** 比较差异 */
            $aDetailInfo =  RecheckQualityDetail::getById($iDetailId);
            $aData['admin_id'] = Admin::user()->name;
            $aData['check_time'] = date('Y-m-d H:i:s');
            $aData = ['score_check' => RecheckQualityDetail::CHECKED];
            if($aDetailInfo['category_check'] == RecheckQualityDetail::CHECKED){
                $aData['is_check'] = RecheckQualityDetail::CHECKED;
            }
            if($aDetailInfo['score'] != $params['score']){
                $aData['is_diff'] =RecheckQualityDetail::ISDIFF;
            }
            RecheckQualityDetail::updateById($iDetailId,$aData);


            $rs = dbPhoto::updatePhotoById($note_id, $data);
            if ($rs) {
                // 正常情况下，一个内容的质量变更为精选之前它的质量一定是优质。如果一个内容从优质调整为精选/普通/差 就需要从待精选池移除
                if (in_array($params['quality'], [dbPhoto::QUALITY_FEATURED, dbPhoto::QUALITY_ORDINARY])) {
                    cFeaturePool::removeNote($note_id); // 从待精选池中移除
                }
                cMachineQuality::removeMark($note_id); // 人工操作后，移除机打标识


                NoteHandle::remarkNote($note_id, "", 1);
                // 添加到队列，更新搜索图片
                cPhotos::delete($note_id);
                CommunityQueue::insertQueue('queue/photo/editphoto', [
                    'photo_id' => $note_id
                ], CommunityQueue::QUEUE_COMMUNITY);

                // 投入wiki服务队列
                \Doraemon\amqp\Queue::insertQueue('queue/wiki/afterAuditContent', [
                    'obj_id' => $note_id,
                ], \Doraemon\amqp\Queue::QUEUE_BIZ);
                $this->pushLevel3Standard($note_id, $qualityLastTime, $params['quality'], $photoInfo);

                if ($data['quality'] == dbPhoto::QUALITY_FEATURED) {
                    // 判断是否曾经打过精选
                    //log信息
                    $onceFeature = 0;
                    $logs = AdmNoteOutlineLog::getLogsByIds($note_id);
                    if ($logs && is_array($logs)) {
                        foreach ($logs as $log) {
                            if (strpos($log['log'], mPhotos::QUALITY_DESC[$params['quality']]) !== false) {
                                $onceFeature = 1;
                            }
                        }
                    }
                    // 如果没有打过精选就发送下行
                    if ($onceFeature == 0) {
                        $noteInfo = Photos::getNoteInfo($note_id);
                        $this->sendMsg($note_id, $noteInfo); // 发送精选下行
                        $this->performTask($noteInfo); // 处理限时任务
                    }
                }
                $channel = AdmNoteOutlineLog::AUDIT_CHANNEL_RECHECK;
//                if ($source == 2){
//                    $channel = AdmNoteOutlineLog::AUDIT_CHANNEL_OPERATE_FEATURE;
//                }
                // log记录
                AdmNote::auditLog($note_id, $params['quality'], Admin::user()->name, $channel);

                $msg = '打分成功';
                //确认品类的标签
                sContentRelatedCategory::changeNoteCategoryAfterGrade($note_id, Admin::user()->id);
            }
        } catch (\Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }
        return compact('code', 'msg');
    }

    //创作者中心3.0-创作力Note
    private function pushLevel3Standard($noteId, $oldQuality, $newQuality, $photoInfo)
    {
        $remarks = ['old_quality' => $oldQuality, 'new_quality' => $newQuality];
        CommunityQueue::insertQueue(tGrowthConfig::MQ_QUEUE_URL, [
            'event_name' => tGrowthConfig::CREAT_GROWTH_NOTE,
            'obj_id' => $noteId,
            'uid' => IdParse::getUid($noteId),
            'remarks' => json_encode($remarks, JSON_UNESCAPED_UNICODE),
        ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);

        //积分操作-评为精选增加积分
        if ($newQuality == mPhotos::QUALITY_FEATURED) {
            //区分装修日记和普通note
            $eventName = $photoInfo['type'] == mPhotos::TYPE_DIARY ? PointConfig::DIARY_QUALITY_FEATURED : PointConfig::NOTE_QUALITY_FEATURED;
            CommunityQueue::insertQueue(PointConfig::MQ_QUEUE_URL, [
                'event_name' => $eventName,
                'obj_id' => $noteId,
                'uid' => IdParse::getUid($noteId),
                'type' => PointConfig::POINT_AWARD
            ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);
        }
    }

    private function _getVideoExpand($videoInfo, $wikiInfos)
    {
        $row = new Row();
        $row->column(4, "<video class='img-responsive container-fluid' controls src='{$videoInfo['basicInfo']['play_url_for_frieza']}' ></video>");
        $content = "<img class='img-responsive float-left center-block col-md-2' src='{$videoInfo['basicInfo']['ori_pic_url']}' />";
        $content = $content . implode("", array_map(function ($snapshotImg) {
                return "<img class='img-responsive float-left center-block col-md-2' src='{$snapshotImg}' />";
            }, (array)$videoInfo['snapshot']));

        $row->column(8, $content);
        $box = new Box('视频信息');
        $box->solid()->content($row->render());
        return $box->render() . ($wikiInfos ? $this->_getWikiExpand($wikiInfos) : '');
    }

    private function _getWikiExpand($wikiInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($wikiInfo) {
            return "<div style='display:inline-block;margin:3px;width:220px;height:220px;'>" .
                "<img src='" . $wikiInfo['cover_img'] . "' height='200' class='img' /><br/>" .
                "<a href='https://beerus.haohaozhu.me/admin/wiki/admList/{$wikiInfo['id']}/edit' target='_blank' >{$wikiInfo['basic_title']}</a>" .
                "</div>";

        }, (array)$wikiInfos)));
        $box = new Box('wiki信息');
        $box->solid()->content($row->render());
        return $box->render();
    }
    private function sendMsg($noteId, $noteInfo)
    {

        $url = 'https://img.haohaozhu.cn//Op-imageShow//2e9f320ku0af0jK00qwy59u?iv=1';
        //如果note类型为视频
        if ($noteInfo['show_type'] == mPhotos::SHOW_TYPE_VIDEO) {
            $videoInfo = $noteInfo['video_info'];
            if ($videoInfo['new_pic_url']) {
                $picList = [
                    $videoInfo['new_pic_url'],
                    'https://img.haohaozhu.cn/Op-imageShow/8e19d308y04j0Qd00qs07h4?iv=1'
                ];
                $result = \Doraemon\tools\ImageCreate::buildImageByTidAndParams(11, $picList);
                $url = $result['url'];
            }

        } else {
            if ($noteInfo['new_pic_url']) {
                $picList = [
                    $noteInfo['new_pic_url'], // 用户首图
                    'https://img.haohaozhu.cn/Op-imageShow/8e19d308y04j0Qd00qs07h4?iv=1'// 盖章
                ];
                $result = \Doraemon\tools\ImageCreate::buildImageByTidAndParams(11, $picList);
                $url = $result['url'];
            }
        }

        Queue::insertQueue('queue/Sysmsg/Send',
            [
                'msgCode' => 405,
                'to_uid' => IdParse::getUid($noteId),
                'msgParams' => [
                    'note_id' => $noteId,
                    'img' => $url ?: null,
                    'link' => HhzNiceLivingUrl::getNoteDetailLink($noteId),
                ]
            ], Queue::QUEUE_DORAEMON
        );
    }

    private function performTask($noteInfo)
    {
        $topicRelatedTask = file_get_contents('/home/adm_rsync_dir/limit_time_task.json');
        $topicRelatedTask = $topicRelatedTask ? json_decode($topicRelatedTask, true) : [];
        $topicIdList = array_keys($topicRelatedTask);
        if (!$noteInfo['topic']['id']) {
            // 基于话题id查询话题标题
            $topicList = TopicActivity::getByIds($topicIdList, ['id', 'title']);
            $topicList = array_column($topicList, null, 'title');
            $topicTitle = array_column($topicList, 'title');
            // 提取内容中的轻话题
            $tagList = Photos::showTag($noteInfo['remark']);
            $tagList = array_column($tagList, 'title');
            // 提取轻话题交集
            $intersectTopicList = array_intersect($topicTitle, $tagList);
            if ($intersectTopicList) {
                $intersectTopicIdList = [];
                foreach ($intersectTopicList as $topic) {
                    $intersectTopicIdList[] = $topicList[$topic]['id'];
                }
                if ($intersectTopicIdList) {
                    foreach ($intersectTopicIdList as $intersectTopicId) {
                        if ($topicRelatedTask[$intersectTopicId]['has_wiki'] && $noteInfo['has_goods'] == 0) {
                            return;
                        }
                        $uid = IdParse::getUid($noteInfo['id']);
                        $taskId = $topicRelatedTask[$intersectTopicId]['task_id'];
                        // 基于任务id查询当前任务的完成度。如果当前任务正在进行中的，并且handle之后为已完成的话，需要发送下行。
                        $hasTaskId = TaskBase::getInfo(['start_time[<]' => time(), 'end_time[>]' => time(), 'id' => $taskId], 'id');
                        if ($hasTaskId) {
                            $taskInfo = mUserTaskInfo::getInfo(['uid' => $uid, 'task_id' => $taskId]);
                            $result = sTask::handleTask($uid, $taskId);
                            if ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_STARTING && $result['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) {
                                // 发送下行
                                Queue::insertQueue('queue/Sysmsg/Send',
                                    [
                                        'msgCode' => 413,
                                        'to_uid' => $uid,
                                        'msgParams' => [
                                            'task_title' => $this->stringTruncated($result['task_title'], 7, 3),
                                            'total' => $taskInfo['total'],
                                        ]
                                    ], Queue::QUEUE_DORAEMON
                                );
                            }
                        }
                    }
                }
            }

        } else {
            if (in_array($noteInfo['topic']['id'], $topicIdList)) {
                if ($topicRelatedTask[$noteInfo['topic']['id']]['has_wiki'] && $noteInfo['has_goods'] == 0) {
                    return;
                }

                $uid = IdParse::getUid($noteInfo['id']);
                $taskId = $topicRelatedTask[$noteInfo['topic']['id']]['task_id'];
                // 基于任务id查询当前任务的完成度。如果当前任务正在进行中的，并且handle之后为已完成的话，需要发送下行。
                $hasTaskId = TaskBase::getInfo(['start_time[<]' => time(), 'end_time[>]' => time(), 'id' => $taskId], 'id');
                if ($hasTaskId) {
                    $taskInfo = mUserTaskInfo::getInfo(['uid' => $uid, 'task_id' => $taskId]);
                    $result = sTask::handleTask($uid, $taskId);
                    if ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_STARTING && $result['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) {
                        // 发送下行
                        Queue::insertQueue('queue/Sysmsg/Send',
                            [
                                'msgCode' => 413,
                                'to_uid' => $uid,
                                'msgParams' => [
                                    'task_title' => $this->stringTruncated($result['task_title'], 7, 3),
                                    'total' => $taskInfo['total'],
                                ]
                            ], Queue::QUEUE_DORAEMON
                        );
                    }
                }
            }
        }
    }

    /**
     * 字符串截断并用指定符号做补充
     * @param $string
     * @param $end
     * @param $length
     * @param string $mode
     * @return string
     */
    private function stringTruncated($string, $end, $length, $mode = '.')
    {
        if ($string) {
            if (strlen($string) <= $end) {
                return $string;
            }
            $repeat = str_repeat($mode, $length);
            return mb_substr($string, 0, $end) . $repeat;
        }
        return '';
    }

}